//通用IPC
const { app, BrowserWindow, ipcMain, clipboard, screen, dialog, shell } = require("electron");
const electronPrompt = require('electron-prompt')
const path = require("node:path");
const browserWindows = {};
let _aboutWindow = undefined
//是否是测试环境
const isDevelopment = !app.isPackaged;

/**
 * 定义了一些通用的IPC监听
 * GENERAL-OPEN-WINDOW : 开启功能窗口
 * GENERAL-SUB-WINDOW-OPEN : 打开父子窗口
 * GENERAL-CLIPBOARD : 复制到剪贴板
 * GENERAL-BAR : 标题栏操作
 */

module.exports = () => {

  //监听打开父子窗口
  ipcMain.on("GENERAL-SUB-WINDOW-OPEN", function (event, arg) {
    const { config } = arg;
    const window = BrowserWindow.getFocusedWindow();
    browserWindow = new BrowserWindow({
      ...config,
      show: false,
      backgroundColor: "#00000000",
      titleBarStyle: "hidden",
      frame: false,
      resizable: false,
      parent: window,
      modal: true,
      webPreferences: {
        preload: path.join(__dirname, "../../preload.js"),
      },
      x: Math.round((screen.getPrimaryDisplay().workAreaSize.width - config.width) / 2),
      y: Math.round((screen.getPrimaryDisplay().workAreaSize.height - config.height) / 2)
    });
    // browserWindow.webContents.openDevTools();
    browserWindow.once("ready-to-show", () => {
      browserWindow.show();
    });
    if (isDevelopment) {
      browserWindow.loadURL(path.join("http://localhost:3321", config.hash));
    } else {
      browserWindow.loadFile(path.join(__dirname, "platform/dist/index.html"), {
        hash: config.hash,
      });
    }
  });

  //监听复制到剪贴板
  ipcMain.on("GENERAL-CLIPBOARD", function (event, arg) {
    const { type, value } = arg;
    if (type == "text") {
      clipboard.writeText(value);
    }
  });

  //监听标题栏操作
  ipcMain.on("GENERAL-BAR", function (event, arg) {
    const { mark } = arg;
    const window = BrowserWindow.getFocusedWindow();
    switch (mark) {
      case "close":
        window.close();
        break;
      case "maximize":
        window.maximize();
        break;
      case "minimize":
        window.minimize();
        break;
      case "restore":
        window.restore();
        break;
      default:
        break;
    }
  });

  //监听prompt
  ipcMain.on('WINDOW-PROMPT', async (event, value) => {
    const { title, content } = value
    const result = await electronPrompt({
      type: 'input',
      title: '输入框',
      label: title,
      default: '',
      height: 185,
      buttonLabels: { ok: '确认', cancel: '取消' },
      alwaysOnTop: true
    });
    event.returnValue = result; // 返回结果给渲染进程
  });

  //监听打开关于面板
  ipcMain.on('OPEN-ABOUT-US-WINDOW', (event, value) => {
    const window = BrowserWindow.getFocusedWindow();
    _aboutWindow = new BrowserWindow({
      width: 540,
      height: 280,
      // titleBarStyle: "hidden",
      backgroundColor: "#00000000",
      frame: false,
      resizable: false,
      parent: window,
      modal: true,
      webPreferences: {
        preload: path.join(__dirname, "../../preload.js"),
      },
    });
    _aboutWindow.loadURL(path.join(__dirname, '../../assets/html/aboutus/index.html'));
    //
  });

  //监听关闭关于面板
  ipcMain.on('CLOSE-ABOUT-US-WINDOW', (event, value) => {
    _aboutWindow?.close()
  });

  //监听选择路径
  ipcMain.on('GENERAL-CHOOSE-DIR-PATH', async (event, value) => {
    const { mark } = value
    const directory = await dialog.showOpenDialog({
      properties: ['openDirectory'] // 只显示目录选择器
    });
    let resPath = directory.filePaths[0]
    if (mark == 'data') {
      resPath = path.join(resPath, 'YuTianDateBase')
    }
    event.returnValue = { mark, value: resPath }
  });

  //监听打开指定路径的资源管理器
  ipcMain.on('GENERAL-OPEN-DIR-PATH', async (event, value) => {
    const { pathCode } = value
    const dirPath = decodeURIComponent(pathCode)
    shell.openPath(dirPath).then(() => {
      console.log('资源管理器已打开');
    }).catch(err => {
      console.error('打开资源管理器时出错:', err);
    });
  });

};
